//
//  DetaileVC.m
//  mentor
//
//  Created by 孙宏峰的MacPro on 2018/7/5.
//  Copyright © 2018年 孙宏峰的MacPro. All rights reserved.
//

#import "DetaileVC.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
#import "ThreeDetailVC.h"
#import "iCloudManager.h"
#import <UIKit+AFNetworking.h>
#import "ShowDocVC.h"
@interface DetaileVC ()<UIWebViewDelegate,UIDocumentPickerDelegate>
@property (strong, nonatomic) UIWebView *webView;
@property (nonatomic,strong) JSContext *context;
@property (nonatomic,copy)NSString *fileName;
@property (nonatomic,copy)NSString * uploadUrl;
@property (nonatomic,strong)NSData *dataObj;
@end

@implementation DetaileVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadWebView:) name:NOTIFICATION_GETURLPARAMETERS object:nil];
          self.navigationItem.leftBarButtonItem = [self getBarButtonItemWithImage:[UIImage imageNamed:@"jiao_back"] withAction:@selector(basePopView) offset:-33];
    self.title = self.navTitle;
    if([self.urlStr rangeOfString:@"?"].location != NSNotFound) {
        self.urlStr = [NSString stringWithFormat:@"%@&token=%@",self.urlStr,[CurrentUser shared].token];
    }else
    {
        self.urlStr = [NSString stringWithFormat:@"%@?token=%@",self.urlStr,[CurrentUser shared].token];
    }
    
    self.urlStr = [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//ios 9以后
    
    NSURL *url = [NSURL URLWithString:self.urlStr];
    
    //TODO::测试
    NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
    
    NSLog(@"request:%@",request);
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
}
- (void)reloadWebView:(NSNotification *)aNotifica
{
    NSMutableDictionary *newDic = [[aNotifica object] mutableCopy];
    NSMutableDictionary *oldParameter = [[self.urlStr getURLParameters:self.urlStr]mutableCopy];
    [oldParameter addEntriesFromDictionary:newDic];

    /*!@brief ****   截取url上所有参数，拼接新的回传参数到url上 */
    /*!@brief   查看当前链接是否包含‘？‘,如果包含？号，需要把？以后的全部截取，如果不包含？可以直接使用
     *
     *
     *
     *
     */
    if([self.urlStr rangeOfString:@"?"].location != NSNotFound) {
        self.urlStr = [self.urlStr componentsSeparatedByString:@"?"].firstObject;
    }
    
    /*!@brief ****   遍历插入所有参数到url上 */
    NSArray *allKeys = [oldParameter allKeys];
    for (int i = 0; i < allKeys.count; i ++) {
        NSString *key = allKeys[i];
        if(i == 0){
            self.urlStr = [NSString stringWithFormat:@"%@?%@=%@",self.urlStr,key,oldParameter[key]];
        }else{
            self.urlStr = [NSString stringWithFormat:@"%@&%@=%@",self.urlStr,key,oldParameter[key]];
        }
    }
    self.urlStr = [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:self.urlStr];
    
    
    //TODO::测试
    NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
    
    NSLog(@"request:%@",request);
    [self.webView loadRequest:request];
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NOTIFICATION_GETURLPARAMETERS object:nil];
}
- (void)basePopView
{
    [self.navigationController popViewControllerAnimated:YES];
}
//通过图片自定义BarButtonItem 偏移
- (UIBarButtonItem *)getBarButtonItemWithImage:(UIImage *)image withAction:(SEL)action offset:(CGFloat)offset
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 44, 44);
    
    [btn setImageEdgeInsets:(UIEdgeInsetsMake(0, offset, 0, 0))];
    [btn setImage:image forState:UIControlStateNormal];
    
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bit = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    return bit;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSLog(@"打印：%@",request.URL.absoluteString);
    NSString *absoluteString = request.URL.absoluteString;
    if(![absoluteString isEqualToString:self.urlStr] && [absoluteString rangeOfString:@"html"].location != NSNotFound) {
        ThreeDetailVC * detailVC = [[ThreeDetailVC alloc]init];
        detailVC.urlStr = absoluteString;
        detailVC.navTitle = [NSString noNull:[[absoluteString getURLParameters:absoluteString]objectForKey:@"title"]];
        [self.navigationController pushViewController:detailVC animated:YES];
        return NO;
    }
    return YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //接受JC的调用
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    self.context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    WS(weakSelf);
    //web端调用客户端支付的方法名字。通知发起
    self.context[@"uploadFileProxy"] = ^(NSString *url){

        NSArray *args = [JSContext currentArguments];
        JSValue *value = args[0];
        weakSelf.uploadUrl = [NSString stringWithFormat:@"%@",value];
        [weakSelf presentDocumentPicker];
    };
    self.context[@"openFileView"] =^(NSString *url)
    {
        NSArray *args = [JSContext currentArguments];
        JSValue *value = args[0];
        dispatch_async(dispatch_get_main_queue(), ^{
            ShowDocVC *docVC = [[ShowDocVC alloc]init];
            docVC.url = [NSString stringWithFormat:@"%@",value];
            [weakSelf.navigationController pushViewController:docVC animated:YES];

        });
    };
}
#pragma mark - customDelegate
#pragma mark - event Response
#pragma mark - private methods
- (void)userCenter

{
//    LoginVC *logVc = [LoginVC new];
//    [self.navigationController presentViewController:logVc animated:YES completion:nil];
}
#pragma mark - getters and setters
- (UIWebView *)webView
{
    if (!_webView ) {
        _webView = [[UIWebView alloc] initWithFrame:(CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64))];
        _webView.delegate = self;
        _webView.scrollView.bounces = NO;
    }
    return _webView;
}
#pragma mark - TEST  Private
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
    self.fileName = [array lastObject];
    self.fileName = [self.fileName stringByRemovingPercentEncoding];
    WS(ws);
    if ([iCloudManager iCloudEnable]) {
        [iCloudManager downloadWithDocumentURL:url callBack:^(id obj) {
            self.dataObj = obj;
/*!@brief ****   接收到文件  开始进行文件上传 */
            [ws uploadFile];
        }];
    }
    
}
- (void)uploadFile
{
    //1.创建会话管理者

    AFHTTPSessionManager * ssmanager = [AFHTTPSessionManager manager];
    ssmanager.requestSerializer.timeoutInterval = 30;
    ssmanager.requestSerializer = [AFHTTPRequestSerializer serializer];
    ssmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [ssmanager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
//    ssmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    
    NSDictionary *dic = @{
                          @"file":self.dataObj,
                          @"token":[CurrentUser shared].token
                          };
    [ssmanager POST:self.uploadUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:self.dataObj name:@"file" fileName:@"file.doc" mimeType:@"*/*"];
    
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"OK");
        NSError *error = nil;
        NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        
        if([resultDictionary[@"code"]integerValue] == 0) {
            
            
            //线程安全的，用此方式，笔者再也没发生过野指针问题。
            //异步主线程执行js方法
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //使用js的window.setTimeout方法执行需要调用的方法
//                // 之后在回调js的方法Callback把内容传出去
//                JSValue *Callback = self.context[@"uploadCallBack"];
//                //传值给web端
//                [Callback callWithArguments:@[self.fileName]];
//                 });
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.context ) {
                    JSValue *callBackValue = self.context[@"uploadCallBack"];
                    [callBackValue callWithArguments:@[self.fileName]];
                }
            });
        }
        NSLog(@"%@",resultDictionary);
//        success(resultDictionary);
//                    success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"NO");
//        NSDictionary * dic = @{@"error":@"error"};
//        failure(dic);
    }];
}

- (void)presentDocumentPicker {
    NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
    
    UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes
                                                                                                                          inMode:UIDocumentPickerModeOpen];
    documentPickerViewController.delegate = self;
    dispatch_async(dispatch_get_main_queue(), ^{
    [self presentViewController:documentPickerViewController animated:YES completion:nil];
    });
    
}
@end
